package com.sh.personnel.controller;

import com.sh.personnel.config.redis.RedisConstant;
import com.sh.personnel.service.impl.IUserServiceImpl;
import com.sh.personnel.util.EmailUtil;
import com.sh.personnel.util.RandomUtil;
import com.sh.personnel.util.result.Result;
import com.sh.personnel.vo.LoginVo;
import com.sh.personnel.vo.RegisterVo;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Email;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 林思浩
 * @date 2020/02/27 15:09
 */
@RestController
public class AuthController {

    @Autowired
    IUserServiceImpl userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    EmailUtil emailUtil;

    //登录授权
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        String token = userService.login(loginVo.getUsername(), loginVo.getPassword());
        return Result.success().setData("token", token);
    }

    //生成验证码
    @GetMapping("/captcha")
    public Result captcha() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        captcha.setLen(2);
        String result = captcha.text();
        String key = RandomUtil.generateUuid();
        redisTemplate.opsForValue().set(RedisConstant.LOGIN_CAPTCHA + key, result, 2, TimeUnit.MINUTES);
        HashMap data = new HashMap();
        data.put("key", key);
        data.put("img", captcha.toBase64());
        return Result.success().setData("captcha", data);
    }

    //注册
    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo register) {
        Boolean bool = userService.register(register);
        return bool ? Result.success() : Result.fail();
    }

    //发送邮箱验证码
    @GetMapping("/register/code")
    public Result sendMailCode(String email) {
        if(EmailUtil.validMail(email)) {
            String code = RandomUtil.randomNumber(5);
            if(emailUtil.sendSimpleMail(email, "注册用户", "您的注册验证码为：" + code + "，请在3分钟内完成注册。")) {
                redisTemplate.opsForValue().set(RedisConstant.EMAIL_CAPTCHA + email, code, 3, TimeUnit.MINUTES);
                return Result.success();
            }
        }
        return Result.fail();
    }

}
